import React, {useEffect, useState} from 'react';
import {Button, Form, Input, Modal, Table, TableProps} from 'antd';
import type {Department} from "@/types/resp/department";
import departmentApi from '@/api/departmentApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import EnterpriseSelector from "@/pages/enterprise/EnterpriseSelector.tsx";


interface DepartmentSelectorProps {
  visible: boolean;
  onDepartmentSelected: (selectedDepartment: { parentDepartmentId?: number; departmentId?: number; parentDepartmentName?: string; departmentName?: string; }) => void;
  onCloseDepartmentSelector: () => void;
}

const DepartmentSelector: React.FC<DepartmentSelectorProps> = ({visible, onDepartmentSelected, onCloseDepartmentSelector}) => {

  const [departmentSelectorForm] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    departmentSelectorForm.resetFields();
  };

  const [data, setData] = useState<Department[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<Department>> = await departmentApi.find(departmentSelectorForm.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<Department> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<Department>['columns'] = [
    {title: '企业名称', dataIndex: 'enterpriseName', key: 'enterpriseName'},
    {title: '部门名称', dataIndex: 'departmentName', key: 'departmentName'},
    {title: '部门描述', dataIndex: 'departmentDescription', key: 'departmentDescription', ellipsis: true},
    {title: '上级部门名称', dataIndex: 'parentDepartmentName', key: 'parentDepartmentName'},
  ];

  const handleRowDoubleClick = (row: Department) => {
    onDepartmentSelected({
      parentDepartmentId: row.id,
      departmentId: row.id,
      parentDepartmentName: row.departmentName,
      departmentName: row.departmentName,
    })
  };

  const selectorFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onCloseDepartmentSelector}>关闭</Button>
    </div>
  );

  useEffect(() => {
    if (visible) {
      onSearch();
    }
  }, [visible]);

  const [enterpriseSelectorVisible, setEnterpriseSelectorVisible] = useState(false);
  const findEnterprise = () => {
    setEnterpriseSelectorVisible(true);
  }
  const handleEnterpriseSelected = (selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) => {
    setEnterpriseSelectorVisible(false)
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      departmentSelectorForm.setFieldsValue(Object.assign(departmentSelectorForm.getFieldsValue(), {
      enterpriseId: selectedEnterprise['enterpriseId'],
      enterpriseName: selectedEnterprise['enterpriseName'],
      }));
    }
  };
  const handleCloseEnterpriseSelector = () => {
    setEnterpriseSelectorVisible(false)
  };

  return (
    <Modal title={"部门信息选择器(双击行选中)"} open={visible} onCancel={onCloseDepartmentSelector}
        width={'var(--modal-width)'} footer={selectorFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      <Form form={departmentSelectorForm} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="enterpriseName" label="企业名称">
          <Input.Search placeholder="请选择企业名称" onSearch={findEnterprise} readOnly={true} />
        </Form.Item>
        <Form.Item name="departmentName" label="部门名称">
          <Input maxLength={64} placeholder="请输入部门名称"/>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
      </Form>
      <Table<Department> columns={columns} dataSource={data} size="small" rowKey={record => record.id}
                         pagination={{ position: ["bottomCenter"] }}
                         onRow={(row) => ({
                           onDoubleClick: (event) => {
                             event.preventDefault();
                             handleRowDoubleClick(row);
                           },
                         })}/>
      <EnterpriseSelector visible={enterpriseSelectorVisible} onEnterpriseSelected={handleEnterpriseSelected} onCloseEnterpriseSelector={handleCloseEnterpriseSelector} />
    </Modal>
  );
};

export default DepartmentSelector;
